package com.dp.service.impl3;

import java.io.File;
import java.io.Serializable;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.persistence.EntityNotFoundException;
import javax.persistence.Query;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dp.pojo.JsonPage;
import com.dp.pub.SysProperty;
import com.dp.util.BookConfig;
import com.dp.util.DataMap;
import com.dp.util.ImageScalee;
import com.dp.util.InterUtil;
import com.dp.vo.NewsContentResource;
import com.dp.vo.NewsContenttitle;
import com.dp.vo.NewsExtendsChannelTitle;
import com.dp.vo.NewsExtendsChannelTitlePK;
import com.dp.vo.NewsResources;
import com.dp.vo.TChannels;
import com.dp.vo.TGenre;
import com.dp.vo.TServiceInfo;
import com.dp.vo.TSubject;
import com.dp.vo.TSubjectResources;

@Service
@Transactional
public class TsubjectServiceImpl3 extends BaseImpl {
	

	/**
	 * 得到主题信息记录,分页
	 * 
	 * @return
	 */
	public Long findAllTsubjectCount(DataMap hashMap,TSubject tsubject) {
		StringBuffer sf = new StringBuffer("SELECT count(t) FROM TSubject t ");
		Object role_id = hashMap.get("role_id");
	    Object user_id = hashMap.get("user_id");
		String userids=(String)hashMap.get("userids");
	    String channelid=hashMap.getMapData("LastChannelS").toString();
	    String tsubject_contentStatus = hashMap.getMapData("tsubject_contentStatus");
	    String tsubject_contenttitlepage = hashMap.getMapData("tsubject_contenttitlepage");
		//按栏目查询
		if(hashMap.get("LastChannelS")!=null){
			sf.append(" ,NewsContenttitle nc,NewsExtendsChannelTitle nect,NewsExtendsChannel nec ");
			sf.append(" WHERE nc.cid=nect.newsContenttitle.cid  and t.contentid=nc.contentid and nect.newsExtendsChannelTitlePK.channleid=nec.channleid  and nec.channelId.channelId='"+channelid+"'");
		}
		if(sf.toString().indexOf("WHERE")==-1){
			sf.append(" WHERE 1=1 ");
		}
		//权限
		if(StringIsNotNull(role_id) && StringIsNotNull(user_id))
	    {
			sf.append(" AND userid='" + user_id + "'");
	    }else if(userids!=null){
	    	sf.append(" AND userid in (" + userids + ")");
		}
		if(hashMap.get("tsubject_contentStatus") != null){
			sf.append(" AND t.contentStatus like '"
						+ tsubject_contentStatus + "'");
		}
		if(hashMap.get("tsubject_contenttitlepage") != null){
			sf.append(" AND t.contentName like '%"
						+ tsubject_contenttitlepage + "%'");
		}
		if (tsubject != null) {
			if (tsubject.getContentName() != null
					&& tsubject.getContentName().toString().trim().length() > 0) {
				sf.append(" AND t.contentName like '%"
						+ tsubject.getContentName() + "%'");
			}
			if (tsubject.getTgenre() != null
					&& tsubject.getTgenre().getGenreId().toString().trim()
							.length() > 0) {
				sf.append(" AND t.tgenre.genreId='"
						+ tsubject.getTgenre().getGenreId() + "'");
			}
			if (tsubject.getContentStatus() != null
					&& tsubject.getContentStatus().toString().trim().length() > 0) {
				sf.append(" AND t.contentStatus='"
						+ tsubject.getContentStatus() + "'");
			}
		}
		logger.info("sf:"+sf.toString());
		Object obj = getSingleResult(sf.toString());
		return obj == null ? 0L : (Long) obj;
	}
	
	/**
	 * 得到主题信息记录,分页
	 * 
	 * @return
	 */
	public List<TSubject> findAllTsubject(DataMap hashMap,TSubject tsubject, Integer firstrow,
			Integer maxrow) {
		StringBuffer sf = new StringBuffer("SELECT t FROM TSubject t ");
		Object role_id = hashMap.get("role_id");
	    Object user_id = hashMap.get("user_id");
		String userids=(String)hashMap.get("userids");
	    String channelid=hashMap.getMapData("LastChannelS").toString();
	    String tsubject_contentStatus = hashMap.getMapData("tsubject_contentStatus");
	    String tsubject_contenttitlepage = hashMap.getMapData("tsubject_contenttitlepage");
		//按栏目查询
		if(hashMap.get("LastChannelS")!=null){
			sf.append(" ,NewsContenttitle nc,NewsExtendsChannelTitle nect,NewsExtendsChannel nec ");
			sf.append(" WHERE nc.cid=nect.newsContenttitle.cid  and t.contentid=nc.contentid and nect.newsExtendsChannelTitlePK.channleid=nec.channleid  and nec.channelId.channelId='"+channelid+"'");
		}
		if(sf.toString().indexOf("WHERE")==-1){
			sf.append(" WHERE 1=1 ");
		}
		//权限
		if(StringIsNotNull(role_id) && StringIsNotNull(user_id))
	    {
			sf.append(" AND userid='" + user_id + "'");
	    }else if(userids!=null){
	    	sf.append(" AND userid in (" + userids + ")");
		}
		if(hashMap.get("tsubject_contentStatus") != null){
			sf.append(" AND t.contentStatus like '" + tsubject_contentStatus + "'");
		}
		if(hashMap.get("tsubject_contenttitlepage") != null){
			sf.append(" AND t.contentName like '%" + tsubject_contenttitlepage + "%'");
		}
		if (tsubject != null) {
			if (tsubject.getContentName() != null
					&& tsubject.getContentName().toString().trim().length() > 0) {
				sf.append(" AND t.contentName like '%"
						+ tsubject.getContentName() + "%'");
			}
			if (tsubject.getTgenre() != null
					&& tsubject.getTgenre().getGenreId().toString().trim()
							.length() > 0) {
				sf.append(" AND t.tgenre.genreId='"
						+ tsubject.getTgenre().getGenreId() + "'");
			}
			if (tsubject.getContentStatus() != null
					&& tsubject.getContentStatus().toString().trim().length() > 0) {
				sf.append(" AND t.contentStatus='"
						+ tsubject.getContentStatus() + "'");
			}
		}
		JsonPage jpage = (JsonPage) hashMap.get("jpage");
		if(jpage!=null && jpage.getSidx()!=null&&!"".equals(jpage.getSidx())){
			sf.append(" order by t."+jpage.getSidx());
			sf.append(" "+jpage.getSord());
		}else{
			sf.append(" order by t.contentUpdateddate desc ");
		}
		logger.info("sf:"+sf.toString());
		return getQueryList(sf.toString(), firstrow, maxrow);
	}
	
	/**
	 * 根据id得到TSubject
	 * 
	 * @param contentid
	 * @return
	 */
	public TSubject getTsubjectByContentid(String contentid) {
		StringBuffer sf = new StringBuffer("SELECT t FROM TSubject t WHERE 1=1");
		sf.append(" AND t.contentid='" + contentid + "'");
		return (TSubject) getSingleResult(sf.toString());
	}

	/**
	 * 主题风格
	 * 
	 * @param type
	 * @return
	 */
	public List<TGenre> findTGenrebyType(String type) {
		StringBuffer sf = new StringBuffer("SELECT t FROM TGenre t WHERE 1=1");
		if (type != null && type.toString().trim().length() > 0) {
			sf.append(" AND t.conentType='" + type + "'");
		}
		return getQueryList(sf.toString());
	}
	
	/**
	 * 获得主题频道列表
	 * @param hashMap
	 * @return  ArrayList
	 */
	public ArrayList getThemeChannelList(DataMap hashMap) {
        String sql = "select  ch.channel_id  ,ch.service_code,ch.channel_name,ch.channel_comment ,ch.function_name,ch.STATUS ,ch.ordered ,ch.created_date,ch.previous_id ,ch.primal_id ,ch.LEVEL ,ch.channel_type  ,ch.channel_hot_topics ,ch.channel_classifying_label" +"  from t_channels ch WHERE 1=1 " +
        		"and channel_type='"+BookConfig.channel_type_subject+"' " +
        		"and status='"+BookConfig.channel_status_enable+"' " +
        		"and (function_name='"+BookConfig.channel_song+"' OR function_name='"+BookConfig.channel_last+"')";
        Object employee_id = hashMap.get("employee_id");
        Object role_id = hashMap.get("role_id");
        if(role_id != null)
        {
	        if (!role_id.equals("") && StringIsNotNull(employee_id)) {
	            sql = "select  ch.channel_id  ,ch.service_code,ch.channel_name,ch.channel_comment ,ch.function_name,ch.STATUS ,ch.ordered ,ch.created_date,ch.previous_id ,ch.primal_id ,ch.LEVEL ,ch.channel_type  ,ch.channel_hot_topics ,ch.channel_classifying_label" +"  from t_channels ch,t_user_channels uc WHERE 1=1 " +
	            "and channel_type='"+BookConfig.channel_type_subject+"' " +
	            "and ch.channel_id=uc.channel_id " +
	            "and status='"+BookConfig.channel_status_enable+"' " +
	            "and (function_name='"+BookConfig.channel_last+"' OR function_name='"+BookConfig.channel_song+"') " +
	            "and uc.employee_id='" + employee_id + "'";
	        }
        }
        try {
            return this.queryALLResultSet(sql);
        } catch (Exception e) {
        	logger.info(" getChannelList fail !!!" +e.getMessage());
            return null;
        }
        
    }
	
	/**
	 * 业务列表
	 * @param hashMap
	 * @return
	 */
	public List<TServiceInfo> getAllServiceInfo(DataMap hashMap) {
		List<TServiceInfo> serviceList = new ArrayList<TServiceInfo>();
		String sql = "select p.serviceid,p.servicename,p.service_code,p.price,p.price_type,p.servicetype,p.access_no,p.port_type,p.content,p.content_type,p.processClass,p.carrier,p.spnumber,p.order_success_msg,p.ctrmand_cmd,p.ctrmand_no,p.starttime" +
				" from t_service_info p,t_user_prices up where p.service_code=up.service_code ";
		Object employee_id = hashMap.get("employee_id");
		Object role_id = hashMap.get("role_id");
		if (role_id != null) {
			if (!role_id.equals("") && StringIsNotNull(employee_id)) {
				sql = sql + " AND employee_id='" + employee_id + "'";
			}
		} else if (role_id == null || role_id.equals("")) {
			sql = "select p.serviceid,p.servicename,p.service_code,p.price,p.price_type,p.servicetype,p.access_no,p.port_type,p.content,p.content_type,p.processClass,p.carrier,p.spnumber,p.order_success_msg,p.ctrmand_cmd,p.ctrmand_no,p.starttime" +
					" from t_service_info p ";
		}
		List list = new ArrayList();

		try {
			list = this.queryALLResultSet(sql);
		} catch (Exception e) {
			logger.info(" getPriceAll fail !!!" + e.getMessage());
			return null;
		}
		for (int i = 0; i < list.size(); i++) {
			DataMap hash = new DataMap();
			hash = (DataMap) list.get(i);
			TServiceInfo tserviceInfo = new TServiceInfo();
			tserviceInfo.setServiceid(Long.parseLong(hash.get("serviceid")
					.toString()));
			tserviceInfo.setServicename(hash.get("servicename").toString());
			tserviceInfo.setPrice(new BigInteger(hash.get("price").toString()));
			serviceList.add(tserviceInfo);
		}
		return serviceList;
	}

	/**
	 * 增加主题
	 * 
	 * @param tsubject
	 *            主题内容
	 * @param tsrlist
	 *            主题资源列表
	 * @param channelid
	 *            主题关联栏目
	 * @return
	 */
	public boolean addTheme(TSubject tsubject, String resourcesid,
		String channelid) {
		// 增加主题内容
		em.persist(tsubject);
		// insert news_contenttitle
		NewsContenttitle newsContenttitle = new NewsContenttitle();
		newsContenttitle.setContentid(tsubject.getContentid());
		newsContenttitle.setContenttitle(tsubject.getContentName());
		String contenticon = SysProperty.getPrep("sysiconid_title");
		if (contenticon == null || contenticon.equals(""))
			contenticon = "1";
		newsContenttitle.setContenticon(Integer.parseInt(contenticon));
		SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String nowtime=fmt.format(new Date());
		String contenttext = ""+InterUtil.rb_jsp.getString("game.name")+":"+tsubject.getContentName()+"@"+InterUtil.rb.getString("src.devcompany")+":"+tsubject.getPubCompany()
			+"@"+InterUtil.rb.getString("src.updatetime")+":"+nowtime+"@"+InterUtil.rb.getString("src.intro")+":"+
			tsubject.getContenInfo()+"";
		newsContenttitle.setContenttext(contenttext);
		//String newstype = InterUtil.rb.getString("src.theme");
		String newstype ="subject";
		newsContenttitle.setNewstype(newstype);
		em.persist(newsContenttitle);
		if (resourcesid != null && !"".equals(resourcesid)) {
			// 关联主题资源
			for (String rid : resourcesid.split(",")) {
				TSubjectResources tsubjectResources = new TSubjectResources();
				tsubjectResources = em.find(TSubjectResources.class, rid);
				tsubjectResources.setContentid(tsubject.getContentid());
				em.persist(tsubjectResources);
				//图片插入news_contenresource
				if("12".equals(tsubjectResources.getType())){
					NewsContentResource ncr=new NewsContentResource();
					List<NewsContenttitle> queryList1=new ArrayList<NewsContenttitle>();
					List<NewsResources> queryList2=new ArrayList<NewsResources>();
					Integer cid=null;
					Integer rid_=null;
					Query query =em.createQuery("select nct from NewsContenttitle nct where contentid='"+tsubject.getContentid()+"'");
					queryList1 = query.getResultList();
					query =em.createQuery("select nr from NewsResources nr where name='"+rid+"'");
					queryList2 = query.getResultList();
					if(queryList1.size()>0){
						cid=queryList1.get(0).getCid();
						ncr.setCid(cid);
						rid_=queryList2.get(0).getRid();
						ncr.setRid(rid_);
						query=em.createNativeQuery("insert into news_contenresource values("+cid+","+rid_+")");
						query.executeUpdate();
					}
				}
			}
		}

		// if(channelid!=null&&!"".equals(channelid)){
		// 主题内容关联栏目
		for (String chid : channelid.split(",")) {
			//频道栏目关联中间表 取自增长channleid
			String jpql="select channleid from NewsExtendsChannel where channelId='"+chid+"'";
			Query query = em.createQuery(jpql);
			Integer channleid=Integer.parseInt(query.getSingleResult().toString());
			jpql="select cid from NewsContenttitle where contentid='"+tsubject.getContentid()+"'";
			query = em.createQuery(jpql);
			Integer cid=Integer.parseInt(query.getSingleResult().toString());
			
			NewsExtendsChannelTitle newsExtendsChannelTitle = new NewsExtendsChannelTitle();
			newsExtendsChannelTitle
					.setNewsExtendsChannelTitlePK(new NewsExtendsChannelTitlePK(
							channleid,
							cid));
			newsExtendsChannelTitle.setContentstatus(0);
			newsExtendsChannelTitle.setIstest(1);
			newsExtendsChannelTitle.setIsnew(1);
			em.persist(newsExtendsChannelTitle);
		}
		// }
		// em.persist(n);
		// em.flush();
		
		return true;
	}

	/**
	 * 增加主题资源
	 * 
	 * @param tsubjectResources
	 */
	public void addTSubjectResources(TSubjectResources tsubjectResources) {
		tsubjectResources=em.merge(tsubjectResources);
		if ("12".equals(tsubjectResources.getType())) {
			// 图片资源插入 news_resource
			NewsResources newsResources = new NewsResources();
			newsResources.setName(tsubjectResources.getResourceid());
			newsResources.setResourcetype(1);	//1:图片，洪涛
			newsResources.setUrl(tsubjectResources.getUrl());
			newsResources.setSize(tsubjectResources.getSize());
			newsResources.setRformat(tsubjectResources.getFormat());
			newsResources.setNewformat(tsubjectResources.getNewformat());
			newsResources.setFullpath(tsubjectResources.getFullpath());
			newsResources = em.merge(newsResources);
		}
		
	}

	/**
	 * 详情 获得已选栏目列表
	 * 
	 * @param channelid
	 * @return
	 */
	public List<TChannels> getSelectedChannelListbyCid(String contentid) {
		List<TChannels> queryList=new ArrayList<TChannels>();
		try {
			String jpql = "SELECT t FROM TChannels t WHERE channelId in (SELECT newsExtendsChannel.channelId" +
							" FROM NewsExtendsChannelTitle n WHERE 1=1 and newsContenttitle.contentid='"
							+ contentid + "')";
			Query query = em.createQuery(jpql);
			queryList = query.getResultList();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return queryList;
	}
	
	/**
	 * 获得资源文件 主题增加时
	 * @param resourcesid
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<TSubjectResources> getTSubjectResources(String resourcesid) {
		List<TSubjectResources> queryList=new ArrayList<TSubjectResources>();
		try {
			
		String resourcesidchar = "";
		for (String r : resourcesid.split(",")) {
			if ("".equals(resourcesidchar)) {
				resourcesidchar = "'" + r + "'";
			} else {
				resourcesidchar += ",'" + r + "'";
			}

		}
		String jpql = "SELECT t FROM TSubjectResources t WHERE 1=1 and resourceid in ("
				+ resourcesidchar + ")";
		Query query = em.createQuery(jpql);
		  queryList = query.getResultList();
		for(TSubjectResources t:queryList){
			
			if("12".equals(t.getType())){
				//页面展示240x320图片
				File target = new File(t.getFullpath().substring(0,t.getFullpath().lastIndexOf("."))+"_240x320."+t.getNewformat());
				if(target.exists()){
					 t.setFullpath(t.getFullpath().substring(0,t.getFullpath().lastIndexOf("."))+"_240x320."+t.getNewformat());
				}
			}
			//页面显示Fullpath
			t.setFullpath(t.getFullpath().replace(SysProperty.getPrep("uploadpath"), ""));
		}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return queryList;
	}

	/**
	 * 根据contentid获得资源文件列表
	 * @param contentid
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<TSubjectResources> getTSubjectResourcesByContentid(
			String contentid) {
		String useragents = "";
		String UA_class_info = "";
		String useragentschar = "";
		List<TSubjectResources> queryList =new ArrayList<TSubjectResources>();
		try {
			
	
		StringBuffer sf = new StringBuffer(
				"SELECT t FROM TSubjectResources t WHERE 1=1");
		sf.append(" AND t.contentid='" + contentid + "'");
		sf.append("  order by type desc");
		Query query = em.createQuery(sf.toString());
		  queryList = query.getResultList();
		for (TSubjectResources t : queryList) {
			useragents = t.getUseragents();
			if (useragents != null) {
				for (String u : useragents.split(",")) {
					if ("null".equals(u)) {
						continue;
					}
					if ("".equals(useragentschar)) {
						useragentschar = "'" + u + "'";
					} else {
						useragentschar += ",'" + u + "'";
					}
				}
				if (!"".equals(useragentschar)) {
					String jpql = "SELECT uaClassInfo FROM TUaClass t WHERE 1=1 and uaClassId in ("
							+ useragentschar + ")";
					query = em.createQuery(jpql);
					List<String> queryList2 = query.getResultList();
					if (queryList2 != null && queryList2.size() > 0) {
						for (String s : queryList2) {
							if ("".equals(UA_class_info)) {
								UA_class_info = s;
							} else {
								UA_class_info += "," + s;
							}
						}
					}
					t.setUseragents(UA_class_info);
				}else{
					t.setUseragents(null);
				}
			}
			if("12".equals(t.getType())){
				//页面展示320x240图片
				File target = new File(t.getFullpath().substring(0,t.getFullpath().lastIndexOf("."))+"_240x320."+t.getNewformat());
				if(target.exists()){
					 t.setFullpath(t.getFullpath().substring(0,t.getFullpath().lastIndexOf("."))+"_240x320."+t.getNewformat());
				}
			}
			//页面显示Fullpath
			t.setFullpath(t.getFullpath().replace(SysProperty.getPrep("uploadpath"), ""));
		}
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (queryList.size() > 0) {
			return queryList;
		}
		return null;
	}

	/**
	 * 修改主题内容
	 * 
	 * @param tsubject
	 * @param channelid
	 * @return
	 */
	public boolean updateTheme(TSubject tsubject, String channelid) {
		// 修改主题内容
		em.merge(tsubject);
		
		// 更新主题内容关联栏目
		SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String nowtime=fmt.format(new Date());
		String contenttext = ""+InterUtil.rb_jsp.getString("game.name")+":"+tsubject.getContentName()+"@"+InterUtil.rb.getString("src.devcompany")+":"+tsubject.getPubCompany()
		+"@"+InterUtil.rb.getString("src.updatetime")+":"+nowtime+"@"+InterUtil.rb.getString("src.intro")+":"+
		tsubject.getContenInfo()+"";
		String jpql = "UPDATE NewsContenttitle SET contenttitle='"+tsubject.getContentName()+"',contenttext='"+contenttext+"',updatetime='"+nowtime+"' WHERE contentid='"+tsubject.getContentid()+"'";
		Query query = em.createQuery(jpql);
		query.executeUpdate();
		jpql = "SELECT cid FROM NewsContenttitle WHERE contentid='"
			+ tsubject.getContentid()+"'";
		query = em.createQuery(jpql);
		Integer cid=Integer.parseInt(query.getSingleResult().toString()) ;
		// 删除原主题内容关联栏目
		jpql = "DELETE FROM NewsExtendsChannelTitle WHERE newsExtendsChannelTitlePK.cid="+cid+"";
		query = em.createQuery(jpql);
		Object obj = query.executeUpdate();
		// if(channelid!=null&&!"".equals(channelid)){
		// 增加主题内容关联栏目
		for (String chid : channelid.split(",")) {
			//频道栏目关联中间表 取自增长channleid
			jpql="select channleid from NewsExtendsChannel where channelId='"+chid+"'";
			query = em.createQuery(jpql);
			Integer channleid=Integer.parseInt(query.getSingleResult().toString());
			
			NewsExtendsChannelTitle newsExtendsChannelTitle = new NewsExtendsChannelTitle();
			newsExtendsChannelTitle
					.setNewsExtendsChannelTitlePK(new NewsExtendsChannelTitlePK(
							channleid,
							cid));
			newsExtendsChannelTitle.setContentstatus(0);
			newsExtendsChannelTitle.setIstest(1);
			newsExtendsChannelTitle.setIsnew(1);
			em.persist(newsExtendsChannelTitle);
		}
		// }
		
		return true;
	}

	/**
	 * 重设栏目
	 * 
	 * @param tsubject
	 * @param channelid
	 * @return
	 */
	public boolean resetConToChannel(TSubject tsubject, String channelid) {
		String jpql = "SELECT cid FROM NewsContenttitle WHERE contentid='"
			+ tsubject.getContentid()+"'";
		Query query = em.createQuery(jpql);
		Integer cid=Integer.parseInt(query.getSingleResult().toString()) ;
		// 删除原主题内容关联栏目
		 jpql = "DELETE FROM NewsExtendsChannelTitle WHERE newsExtendsChannelTitlePK.cid="
			+ cid+"";
		 query = em.createQuery(jpql);
		Object obj = query.executeUpdate();
		// if(channelid!=null&&!"".equals(channelid)){
		// 增加主题内容关联栏目
		for (String chid : channelid.split(",")) {
			//频道栏目关联中间表 取自增长channleid
			jpql="select channleid from NewsExtendsChannel where channelId='"+chid+"'";
			query = em.createQuery(jpql);
			Integer channleid=Integer.parseInt(query.getSingleResult().toString());
			
			NewsExtendsChannelTitle newsExtendsChannelTitle = new NewsExtendsChannelTitle();
			newsExtendsChannelTitle
					.setNewsExtendsChannelTitlePK(new NewsExtendsChannelTitlePK(
							channleid,
							cid));
			newsExtendsChannelTitle.setContentstatus(0);
			newsExtendsChannelTitle.setIstest(1);
			newsExtendsChannelTitle.setIsnew(1);
			em.persist(newsExtendsChannelTitle);
		}
		// }
		
		return true;
	}
	
	/**
	 * 主题内容下线
	 * @param contentids
	 * @return
	 */
	public boolean disableContent(String contentids) {
		String cidstr = this.getCidStrForContentidGLobal(contentids);
		// 修改主题内容状态为 disable
		String jpql = "UPDATE TSubject SET contentStatus='disable' WHERE contentid in (" + contentids + ")";
		log.info(jpql);
		Query query = em.createQuery(jpql);
		query.executeUpdate();
		// 更新主题内容关联栏目
		jpql = "UPDATE NewsExtendsChannelTitle SET contentstatus=3 WHERE newsExtendsChannelTitlePK.cid in ("+ cidstr+")";
		log.info(jpql);
		query = em.createQuery(jpql);
		query.executeUpdate();
		return true;
	}

	/**
	 * 更新主题内容状态  提交审核
	 * 
	 * @param strIdList
	 * @param status
	 * @return
	 */
	public boolean updateThemeStatus(String strIdList, String status) {
		try {
			// 更新主题内容状态
			String jpql = "UPDATE TSubject SET contentStatus='" + status
					+ "' WHERE contentid in (" + strIdList + ")";
			Query query = em.createQuery(jpql);
			query.executeUpdate();
		} catch (Exception e) {
			return false;
		} 
		return true;
	}
	
	/**
	 * 审核主题，通过
	 * @param user_id
	 * @param contentids
	 * @return
	 */
	public boolean auditThemesPass(String user_id, String contentids) {
		contentids = contentids.replaceAll("'","");	//原id是以"'"单引号包括在内的
		for (String contentid : contentids.split(",")) {
			// 转换图片
			String resourceid = scaleImage(contentid);
			if (resourceid == null) {
				return false;
			}
			
			// 更新主题内容状态 pass
			String jpql = "UPDATE TSubject SET contentStatus='pass',audituser='"+user_id+"',unpassCause=null WHERE contentid='"
					+ contentid + "'";
			Query query = em.createQuery(jpql);
			Object obj = query.executeUpdate();
			
			// 更新 news_contenttitle.contenticon
			String contenticon = SysProperty.getPrep("sysiconid_title");
			if (contenticon == null || contenticon.equals(""))
				contenticon = "1";
			
			if("".equals(resourceid)){
				//没有图片
				jpql = "update NewsContenttitle set contenticon='"+contenticon+"' where contentid='"
					+ contentid
					+ "'";
			}else{
				jpql = "update NewsContenttitle set contenticon=(select max(rid) from NewsResources where name='"
					+ resourceid
					+ "') where contentid='"
					+ contentid
					+ "'";
			}
			
			query = em.createQuery(jpql);
			query.executeUpdate();
			TSubject tsubject=new TSubject();
			tsubject = em.find(TSubject.class, contentid);
			jpql = "SELECT cid FROM NewsContenttitle WHERE contentid='"
				+ tsubject.getContentid()+"'";
			query = em.createQuery(jpql);
			Integer cid=Integer.parseInt(query.getSingleResult().toString()) ;
			// 更新主题内容关联栏目 contentstatus=2
			jpql = "UPDATE NewsExtendsChannelTitle SET contentstatus=2 WHERE newsExtendsChannelTitlePK.cid="
				+ cid+"";
			query = em.createQuery(jpql);
			obj = query.executeUpdate();
		}
		
		return true;
	}
	
	/**
	 * 审核主题，未通过
	 * @param user_id
	 * @param contentids
	 * @param cause
	 * @return
	 */
	public boolean auditThemesUnPass(String user_id, String contentids, String cause) {
		try {
				// 更新主题内容状态 nopass
			String jpql = "UPDATE TSubject SET contentStatus='unpass',audituser='"+user_id+ "',unpassCause='"+ cause + "' WHERE contentid in (" + contentids + ")";
			Query query = em.createQuery(jpql);
			query.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * 审核通过后转换图片到 news_resources
	 * 
	 * @param contentid
	 * @param db
	 * @return
	 */
	public String scaleImage(String contentid) {
		String jpql = "select t from TSubjectResources t where type='12' and contentid='"
				+ contentid + "'";
		List<TSubjectResources> tresList = null;
		String resourceid = "";
		try {
			Query query = em.createQuery(jpql);
			tresList = query.getResultList();
			if (tresList.size() > 0) {
				// 转换一张icon
				TSubjectResources tsubjectResources = tresList.get(0);
				resourceid = tsubjectResources.getResourceid();
				String fullpath = tsubjectResources.getFullpath();
				ImageScalee ims = new ImageScalee();
				String imageSizeScaleStr = SysProperty
						.getPrep("news_imagesizescale");
				String imageFormatScaleStr = SysProperty
						.getPrep("news_imageformatscale");
				if (imageFormatScaleStr == null
						|| imageFormatScaleStr.equals(""))
					imageFormatScaleStr = "png";
				String[] imageSizeScaleAry = imageSizeScaleStr.split(",");
				String[] imageFormatScaleAry = imageFormatScaleStr.split(",");
				if (imageSizeScaleAry != null && imageSizeScaleAry.length > 0) {
					for (String imageSizeScale : imageSizeScaleAry) {
						String screenWidHei = imageSizeScale.split("@")[0];
						String picWidHei = imageSizeScale.split("@")[1];
						int screenWidth = Integer.parseInt(screenWidHei
								.split("x")[0]);
						int screenHeight = Integer.parseInt(screenWidHei
								.split("x")[1]);
						int width = Integer.parseInt(picWidHei.split("x")[0]);
						int height = Integer.parseInt(picWidHei.split("x")[1]);
						if (imageFormatScaleAry != null
								&& imageFormatScaleAry.length > 0)
							for (String imageFormatScale : imageFormatScaleAry){
								try {
									ims.compressPicsScale(fullpath, width, height,
											imageFormatScale, screenWidth,
											screenHeight);
								} catch (Exception e) {
									logger.error(e.getMessage());
									return null;	
								}
							}
								
					}
				}
				//删除原图标
				// 如果存在 删除原图标 （之前上线过 下线后再修改 再提交审核）
				jpql = "select n from TSubjectResources t,NewsResources n where n.resourcetype is null and contentid='"
				+ contentid + "' and n.name=t.resourceid";
				query = em.createQuery(jpql);
				List<NewsResources> iconlist=query.getResultList();
				for(NewsResources resources_temp:iconlist){
					em.remove(resources_temp);
				}
				
				String scaleFullPath = fullpath.replace(".", "-p.");
				NewsResources newsResources=new NewsResources();
				newsResources.setName(resourceid);
				newsResources.setResourcetype(1);	//0908 hongtao
				newsResources.setNewformat(imageFormatScaleStr);
				newsResources.setFullpath(scaleFullPath);
				em.merge(newsResources);
			}
		} catch (Exception e) {
			logger.info(" parse content icon fail !!!" + e.getMessage());
			e.printStackTrace();
			return null;
		}
		return resourceid;
	}
	
	public String getSpcodeByUserId(String userid)
	{
		String sql = "select te.sp_code from t_employee te, t_user tu where tu.employee_id=te.employee_id and tu.user_id='" + userid + "'";
		String s = "";
		try {
			s = this.queryOne(sql);
		} catch (Exception e) {
			logger.info(" getSpcodeByUserId excute sql : " +sql);
			logger.info(" getSpcodeByUserId fail !!!" +e.getMessage());
			e.printStackTrace();
			return "nospcode";
		}
		return s;
	}
	
	@SuppressWarnings("unchecked")
	public Object get(Class clazz, Serializable id) {
		Object o =null;
		try {
		
			o= this.em.find(clazz, id);
		}catch (Exception e) {
			e.printStackTrace();
		}
		if (o == null) {
			String msg = "Uh oh, '" + clazz + "' object with id '" + id
					+ "' not found...";
			logger.warn(msg);
			throw new EntityNotFoundException(msg);
		}
		
		return o;
	}

	public static boolean StringIsNotNull(Object str) {
        boolean b = false;
        try {
            if (!str.equals("") && !str.equals("null")) {
                b = true;
            }
        } catch (Exception e) {
        }
        return b;
    }

    //add 1119 select channel update
    public DataMap buildLastChannelMap()
    {
    	String sql = "SELECT channel_id,channel_name,function_name,previous_id FROM t_channels t";
    	HashMap<String,String> childIdAndPreiousId = new HashMap<String,String>();
    	HashMap<String,String> idAndName = new HashMap<String,String>();
    	DataMap result = new DataMap();
    	List chList = null;
    	try {
			chList = this.queryALLResultSet(sql);
		} catch (Exception e) {
			log.info(" buildChChildIdAndPreviousIdMap fail !!!" +e.getMessage());
			e.printStackTrace();
			return null;
		}
		//首先建立两个map准备数据
		for(int i=0;i<chList.size();i++)
		{
			HashMap hashMap = (HashMap)chList.get(i);
			String channel_id = (String)hashMap.get("channel_id");
			String chName = (String)hashMap.get("channel_name");
			String fnName = (String)hashMap.get("function_name");
			String previous_id = (String)hashMap.get("previous_id");
			//先将id和name装入map
			idAndName.put(channel_id, chName);
			//channel如果是normal或者first,就装入map,key是channel_id,value是
			if(fnName.equals(BookConfig.channel_first) || fnName.equals(BookConfig.channel_normal))
			{
				childIdAndPreiousId.put(channel_id, previous_id);
			}
		}
		//build map,key:channleid value:previousid+name
		for(int i=0;i<chList.size();i++)
		{
			HashMap hashMap = (HashMap)chList.get(i);
			String channel_id = (String)hashMap.get("channel_id");
			String chName = (String)hashMap.get("channel_name");
			String fnName = (String)hashMap.get("function_name");
			String previous_id = (String)hashMap.get("previous_id");
			//如果是normal或者first,就装入map,key是channel_id,value是
			if(fnName.equals(BookConfig.channel_last) || fnName.equals(BookConfig.channel_song))
			{
				String previousChName = idAndName.get(previous_id);
				chName = chName+"="+previousChName;
				chName = getValue(childIdAndPreiousId,idAndName,previous_id,chName);
				//最上一级的频道名称必然是news,把news过滤掉
				chName = chName.substring(0,chName.lastIndexOf("="));
				String[] tmp = chName.split("=");
				String value = "";
				for(int j=tmp.length-1;j>=0;j--)
				{
					value=value+tmp[j]+"--";
				}
				value = value.substring(0,value.length()-2);
				result.put(channel_id, value);
			}
		}
    	return result;
    }
    
    private String getValue(HashMap<String,String> idmap,HashMap<String,String> namemap,String key,String result)
    {
    	String parentid = idmap.get(key);
    	String parentname = namemap.get(parentid);
    	if((key != null && parentid!=null) && !parentid.equals(key))
    	{
    		result = result+"="+parentname;
    		return getValue(idmap,namemap,parentid,result);
    	}
    	else
    	{
    		return result;
    	}
    }

    //add for multi catalog
    public ArrayList getChannelPlatform()
    {
    	ArrayList result = new ArrayList();
    	//1 取得所有生效的catalog对应的catalogchannelid
    	String sql = "SELECT ncc.channelid,ncp.mplatform,ncp.magent,ncp.mserialnum,ncp.mlocale,ncp.catlogid" +
    			" FROM news_catlog nc left join news_catlog_platform ncp on ncp.catlogid=nc.catlogid," +
    			"news_catlog_channel ncc where nc.isnowpublish in (1,2) and nc.catlogid=ncc.catlogid";
    	ArrayList catalogChannelidAndPlatformList = new ArrayList();
    	try {
    		catalogChannelidAndPlatformList = this.queryALLResultSet(sql);
    		if(catalogChannelidAndPlatformList.size()>0)
    		{
	    		for(int i=0;i<catalogChannelidAndPlatformList.size();i++)
	    		{
	    			DataMap lastChannelAndPlatform = new DataMap();
	    			HashMap hashmap = (HashMap)catalogChannelidAndPlatformList.get(i);
	    			String catalogChannelid = (String)hashmap.get("channelid");
	    			String platforminfo = InterUtil.rb.getString("src.gameplatform")+hashmap.get("mplatform")+"."+
	    			InterUtil.rb.getString("src.gamedistributor")+hashmap.get("magent")+"."+InterUtil.rb.getString("src.clientsn")+
	    			hashmap.get("mserialnum")+"."+InterUtil.rb.getString("src.languagearea")+hashmap.get("mlocale");
	    			sql = "SELECT nc.channel_id FROM news_buttons nb,news_extends_firstchannel_buttons nfb,news_contenttype nc where " +
	    					"nfb.channelid="+catalogChannelid+" and nc.newscontenttype=nb.buttoncontenttype and nfb.buttonid=nb.buttonid";
	    			ArrayList tchannelIdList = this.queryALLResultSet(sql);
	    			if(tchannelIdList.size()>0)
	    			{
	    				//首先要判断结果集里的channel是否最后一级
	    				for(int j=0;j<tchannelIdList.size();j++)
	    				{
	    					DataMap tmpMap = (DataMap)tchannelIdList.get(j);
	    					String tch_id = tmpMap.getMapData("channel_id");
	    					if(tch_id == null || tch_id.equals(""))
	    						continue;
	    					sql = "select function_name from t_channels where channel_id='"+tch_id+"'";
	    					String functionname = this.queryOne(sql);
	    					//if最后一级 放到map里 key是最后一级的id value是platforminfo
	    					if(functionname.toUpperCase().equals("LAST") || functionname.toUpperCase().equals("CHANNELSONG"))
	    						lastChannelAndPlatform.put(tch_id, platforminfo);
	    					//不是 递归查询
	    					else
	    						buildLastChannelAndPlatform(tch_id,platforminfo,lastChannelAndPlatform);
	    				}
	    			}
	    			result.add(lastChannelAndPlatform);
	    		}
    		}
		} catch (Exception e) {
			log.info(" getChannelPlatform fail !!!" +e.getMessage());
			e.printStackTrace();
		}
    	return result;
    }
    
    private void buildLastChannelAndPlatform(String tch_id,String platforminfo,DataMap lastChannelAndPlatform)
    {
    	String sql = "SELECT channel_id,function_name FROM t_channels where previous_id='"+tch_id+"'";
    	try {
			ArrayList chList = this.queryALLResultSet(sql);
			for(int i=0;i<chList.size();i++)
			{
				HashMap hashMap = (HashMap)chList.get(i);
				String fnName = (String)hashMap.get("function_name");
				String channel_id = (String)hashMap.get("channel_id");
				if(fnName.toUpperCase().equals("LAST") || fnName.toUpperCase().equals("CHANNELSONG"))
					lastChannelAndPlatform.put(channel_id, platforminfo);
				else
					buildLastChannelAndPlatform(channel_id,platforminfo,lastChannelAndPlatform);
			}
		} catch (Exception e) {
			log.info(" buildLastChannelAndPlatform fail !!!" +e.getMessage());
			e.printStackTrace();
		}
    }

	public ArrayList<DataMap> findAllLastChannel(DataMap hashMap) {
		Object roleId = hashMap.get("role_id");
		Object userId = hashMap.get("user_id");
		String userids = (String)hashMap.get("userids");
		//root
		String findSql = "select  ch.channel_id  ,ch.service_code,ch.channel_name,ch.channel_comment ,ch.function_name,ch.STATUS ,ch.ordered ,ch.created_date,ch.previous_id ,ch.primal_id ,ch.LEVEL ,ch.channel_type  ,ch.channel_hot_topics ,ch.channel_classifying_label" +"  from t_channels ch WHERE 1=1 " +
				" and channel_type='"+BookConfig.channel_type_subject+"' " +  
				" AND (function_name='"+BookConfig.channel_last+"' OR function_name='"+BookConfig.channel_song+"') ";
		//normal user
		if(roleId != null && !roleId.equals(""))
		{
			findSql = "select  ch.channel_id  ,ch.service_code,ch.channel_name,ch.channel_comment ,ch.function_name,ch.STATUS ,ch.ordered ,ch.created_date,ch.previous_id ,ch.primal_id ,ch.LEVEL ,ch.channel_type  ,ch.channel_hot_topics ,ch.channel_classifying_label" +"  from t_channels ch,t_user_channels uc WHERE ch.channel_id=uc.channel_id " +
					" and channel_type='"+BookConfig.channel_type_subject+"' " + 
		    		" and (function_name='"+BookConfig.channel_last+"' OR function_name='"+BookConfig.channel_song+"')  " +
		    		" and uc.employee_id=(SELECT employee_id FROM t_user where user_id='" + userId + "')";
		}else if(userids!=null){
			findSql = "select DISTINCT  ch.channel_id  ,ch.service_code,ch.channel_name,ch.channel_comment ,ch.function_name,ch.STATUS ,ch.ordered ,ch.created_date,ch.previous_id ,ch.primal_id ,ch.LEVEL ,ch.channel_type  ,ch.channel_hot_topics ,ch.channel_classifying_label" +"  from t_channels ch,t_user_channels uc WHERE ch.channel_id=uc.channel_id " +
	    		" and status='"+BookConfig.channel_status_enable+"'" +
				" and channel_type='"+BookConfig.channel_type_subject+"' " + 
	    		" and (function_name='"+BookConfig.channel_last+"' OR function_name='"+BookConfig.channel_song+"')  " +
	    		" and uc.employee_id in (SELECT employee_id FROM t_user where user_id in (" + userids + "))";
		}
		try {
			return this.queryALLResultSet(findSql.toString());
		} catch (Exception e) {
			logger.error(" findAllLastChannel fail !!!" +e.getMessage());
			return null;
		}
	}

	/**
	 * 获得栏目列表
	 * 
	 * @param hashMap
	 * @return
	 */
	public List<TChannels> getChannelList(DataMap hashMap) {
		Object roleId = hashMap.get("role_id");
		Object userId = hashMap.get("user_id");
		String userids = (String)hashMap.get("userids");
		
		String jpql = "SELECT ch FROM TChannels ch WHERE ch.status='"
				+ BookConfig.channel_status_enable + "' AND ch.channelType='"+BookConfig.channel_type_subject+"'  AND (functionName='"
				+ BookConfig.channel_song + "' OR functionName='"
				+ BookConfig.channel_last + "')";
		if (roleId != null && !roleId.equals("")) {
			jpql = "select ch from TChannels ch,TUserChannels uc,TUser u WHERE ch.channelId=uc.channelId AND uc.employeeId=u.employeeId AND ch.status='"
					+ BookConfig.channel_status_enable + "' AND ch.channelType='"+BookConfig.channel_type_subject+"' AND (ch.functionName='"
					+ BookConfig.channel_last + "' OR ch.functionName='" + BookConfig.channel_song
					 + "' AND u.userId='" + userId+ "')";
		}else if(userids!=null){
			jpql = "select DISTINCT ch from TChannels ch,TUserChannels uc,TUser u WHERE ch.channelId=uc.channelId AND uc.employeeId=u.employeeId AND ch.status='"
				+ BookConfig.channel_status_enable + "' AND ch.channelType='"+BookConfig.channel_type_subject+"' AND (ch.functionName='"
				+ BookConfig.channel_last + "' OR ch.functionName='" + BookConfig.channel_song
				 + "' AND u.userId in (" + userids+ "))";
		}
		try {
			return this.getQueryList(jpql);
		} catch (Exception e) {
			logger.error(" findAllLastChannel fail !!!" +e.getMessage());
			return null;
		}
	}
	
	

    
//    public DataMap getResource(String  resourceid) {
//
//    	//String sql = "select * from t_subject_resources where resourceid= '" + resourceid + "'";
//        try {
//        	return null;
//           // return queryOneRow(sql);
//        } catch (Exception e) {
//        	log.info(" getResource fail !!!" +e.getMessage());
//            return null;
//        }
//    }
    public ArrayList getMobileCompany(DataMap hashMap) {
        String sql = "SELECT t.com_id,t.com_name FROM t_mobile_company_info t where 1=1 ";
        try {
            return queryALLResultSet(sql);
        } catch (Exception e) {
        	log.info(" getMobileCompany fail !!!" +e.getMessage());
            return null;
        }
    }
    
//    public ArrayList getCurrentUaClassList(String resourceid) {
//    	String sql = "";
//    	if(resourceid != null && !resourceid.equals(""))
//        	sql = "select * FROM t_ua_class where FIND_IN_SET(ua_class_id,( SELECT useragents FROM t_subject_resources  where resourceid='"+resourceid+"')) >0 ";
//        try {
//            return queryALLResultSet(sql);
//        } catch (Exception e) {
//        	log.info(" get current uaclass list fail !!!" +e.getMessage());
//        	return null;
//        }
//    }
	    
    public ArrayList getUaClass(String comid) {
        String sql = "SELECT t.UA_CLASS_ID,t.UA_CLASS, t.ua_class_info FROM t_ua_class t where com_id= " + comid;
        
        try {
            return queryALLResultSet(sql);
        } catch (Exception e) {
        	log.info(" getUaClass fail !!!" +e.getMessage());
            return null;
        }
    }
    
    public String getCurrentUaClass(String resourceid) {
    	String sql = "";
    	if(resourceid != null && !resourceid.equals(""))
        	sql = "SELECT useragents FROM t_subject_resources t where resourceid='" + resourceid + "'";
        try {
            return queryOne(sql);
        } catch (Exception e) {
        	log.info(" get current uaclass id fail !!!" +e.getMessage());
        	return "";
        }
    }
    
    public boolean updateResourceUa(String useragent,String resourceid) {
        String sql = "update t_subject_resources set useragents='"+useragent+"' where resourceid='" + resourceid + "'";
        try {
            return execUpdate(sql);
        } catch (Exception e) {
        	log.info(" updateResourceUa fail !!!" +e.getMessage());
        	return false;
        }
    }
    
    
    public boolean delUaclassByResid(String resourceid,String uaclassid)
    {
    	String sql = "";
    	if(resourceid != null && !resourceid.equals(""))
        	sql = "select useragents FROM t_subject_resources where resourceid ='"+resourceid+"'";
    	try {
	    	String useragents = queryOne(sql);
	    	if(uaclassid != null)
	    	{
	    		String uaclassidstr = uaclassid + ",";
	    		String uaclsidstr = ","+uaclassid;
	    		if(useragents.contains(uaclassidstr))
	    			useragents = useragents.replace(uaclassidstr, "");
	    		else if(useragents.contains(uaclsidstr))
	    			useragents = useragents.replace(uaclsidstr, "");
	    		else if(useragents.contains(uaclassid))
	    			useragents = useragents.replace(uaclassid, "");
	    	}
	    	sql = "update t_subject_resources set useragents='"+useragents+"' where resourceid='"+resourceid+"'";
	    	return execUpdate(sql);
        } catch (Exception e) {
        	log.info(" delUaclassByResid fail !!!" +e.getMessage());
        	return false;
        }
        
    }
	

}
